package top.swimmer.tokenizer.core;

import top.swimmer.tokenizer.dictionary.DictionaryFactory;
import top.swimmer.tokenizer.entities.Word;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by xiaoyou on 17-1-6.
 */
public class ForwardMinimumMatching extends AbstractSegmentation {

    @Override
    public List<Word> segmentation(String text) {
        Queue<Word> results = new LinkedList<>();
        int textLength = text.length();
        int wordMinLength = 2; //最小词长 这里不考虑单字的词
        int start = 0;

        while (start < textLength) {
            int currentLength = wordMinLength; // 从start处开始 从长度为2开始查找可分的词
            boolean isSeg = false;
            while (start + currentLength <= textLength) {
                if (getDictionary().contains(text, start, currentLength)) {
                    addWord(results, text, start, currentLength);
                    isSeg = true;
                    break;
                } else if (++currentLength > getDictionary().getMaxWordLength()) { // 没有的话就让currentLength+1，如果大于词典中最长的词就跳出循环
                    break;
                }
            }

            if (isSeg) {
                start += currentLength;
            } else {
                addWord(results, text, start++, 1);
            }
        }

        return new ArrayList<>(results);
    }

    public static void main(String[] args) {
        ForwardMinimumMatching minimumMatching = new ForwardMinimumMatching();
        System.out.println(minimumMatching.segmentation("南"));
        System.out.println(minimumMatching.segmentation("贵是"));
        System.out.println(minimumMatching.segmentation("贵是贵是贵是贵是贵是贵是贵是贵是"));
        System.out.println(minimumMatching.segmentation("南京市长江大桥"));
        System.out.println(minimumMatching.segmentation("贵是哈南京市长江大桥哈贵是"));
        System.out.println(minimumMatching.segmentation("我们都有一个家"));
        System.out.println(minimumMatching.segmentation("阿基受到法律看还是来开发"));
        System.out.println(minimumMatching.segmentation("长春市长王铁路"));
        System.out.println(minimumMatching.segmentation("自如有家是一家创造品质租住产品的互联网公司"));
        System.out.println(minimumMatching.segmentation("无论是后来故事怎么了"));
        System.out.println(minimumMatching.segmentation("也要让后来人生精彩着"));
        System.out.println(minimumMatching.segmentation("无论是后来故事怎么了，也要让后来人生精彩着！"));
        System.out.println(minimumMatching.segmentation("也要！@#让后\"来人%……&生精彩着"));
        System.out.println(minimumMatching.segmentation("他不管三七二十一就骂她是二百五，我就无语了，真是个二货。他还问我：“杨老师，‘二货’是什么意思？”"));
    }
}
